import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.建立链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //主机地址
        connectionFactory.setHost("139.9.116.124");
        //端口号
        connectionFactory.setPort(5672);
        //用户名
        connectionFactory.setUsername("test");
        //密码
        connectionFactory.setPassword("123456");
        //虚拟机
        connectionFactory.setVirtualHost("test");
        //连接建立
        Connection connection = connectionFactory.newConnection();
        //2.开启信道
        Channel channel = connection.createChannel();
        //4.消费消息
        /**参数声明
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * queue:队列名
         * autoAck:自动确认
         * callback：接收到消息执行逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel){
            //从队列中收到消息，就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //TODO
                System.out.println("接收的消息："+new String(body));
            }
        };
        channel.basicConsume("test1",true,consumer);
        //等待程序执行完成
        Thread.sleep(2000);
        //5.释放资源
        channel.close();
        connection.close();
    }
}
